from django.shortcuts import render, redirect
from django.core.exceptions import ObjectDoesNotExist

from django.http import HttpResponse
import json, datetime
from sale_web import models

import sale_web.aesmysql as aesmysql

import sale.settings as settings


# Create your views here.

cryptoCode = 'end6eEBYR1lE'

def index(request):
    return render(request, 'index.html')


def searchMobile(request):
    return render(request, 'searchMobile.html')


def onSearchMobile(request):
    print("in onsearch")

    param_phone_no = request.GET.get('key')
    try:
        user_yhxx = models.yhxx.objects.get(phone_no=aesmysql.encrypt_mysql(cryptoCode, param_phone_no))
    except ObjectDoesNotExist:
        user_yhxx = None

    # 判断是否非空
    if user_yhxx is not None:
        print(user_yhxx.prod_name)
        result = {"code": 0, "Result": [
            {"Disabled": False, "Group": None, "Selected": False, "Text": user_yhxx.prod_name, "Value": user_yhxx.id}]}
    else:
        result = {"code": 0, "Result": []}

    # json返回为中文
    return HttpResponse(json.dumps(result, ensure_ascii=False), content_type="application/json,charset=utf-8")


def callSale(request):
    return render(request, 'callSale.html')


def onGetCallSaleInfo(request):
    prod_id = request.GET.get("prod_id")
    print('callSaleId: ' + prod_id)

    res = {'code': 0, 'msg': None,
           'data': {'ID': None, 'PROD_ID': 0, 'PROD_ID_END': 0, 'PROD_NAME_END': None, 'PROD_NAME': '--选择活动类型--',
                    'PROD_LIST': [{'ID': 88, 'PROD_NAME': '198元大流量资费推荐',
                                   'CALL_REMARK': '推荐您升级198元大流量套餐，可享受国内流量40GB+1000分钟语音通话（500分钟国内+500分钟省内）+两条100M的宽带，现在很多用户都在办理，真的很划算。流量超过40G后将限速。',
                                   'OTHER_REMARK': None, 'END_TIME': '0001-01-01T00:00:00',
                                   'END_TIME_STR': '0001-01-01 00:00:00', 'RECYCLE_HOURS': 0, 'STATUS': None,
                                   'PUB_TIME': '0001-01-01T00:00:00', 'FORBID_TIME': '0001-01-01T00:00:00',
                                   'FORBID_TIME_STR': '00:00:00', 'ALLOW_CALL_CNT': 0, 'CALLED_HOURS': 0,
                                   'CLIENT_NAME': None, 'SERVER_NAME': None, 'RECORDS': 0},
                                  {'ID': 82, 'PROD_NAME': '4G双降大流量5折购',
                                   'CALL_REMARK': '推荐您【用98元移动大流量套餐领300元话费！】，300元话费活动，每月赠送50元，连续赠送6个月，每月最低消费98元，可享受国内流量20GB+300分钟语音通话（150分钟国内+150分钟省内）+100M的宽带，现在很多用户都在办理，加上赠送话费后，消费跟您现在差不多，但语音、流量比原来资费多，还可以送一条宽带。流量超过20G后才限速。赠送的话费于每月23日至28日前到帐，赠送的话费抵扣本月的消费，活动期内资费不能更改或取消，6个月活动结束后您可自行更改其他资费套餐。',
                                   'OTHER_REMARK': None, 'END_TIME': '0001-01-01T00:00:00',
                                   'END_TIME_STR': '0001-01-01 00:00:00', 'RECYCLE_HOURS': 0, 'STATUS': None,
                                   'PUB_TIME': '0001-01-01T00:00:00', 'FORBID_TIME': '0001-01-01T00:00:00',
                                   'FORBID_TIME_STR': '00:00:00', 'ALLOW_CALL_CNT': 0, 'CALLED_HOURS': 0,
                                   'CLIENT_NAME': None, 'SERVER_NAME': None, 'RECORDS': 0},
                                  {'ID': 86, 'PROD_NAME': '148元大流量资费推荐',
                                   'CALL_REMARK': '推荐您升级148元大流量套餐，可享受国内流量30GB+600分钟语音通话（300分钟国内+300分钟省内）+100M的宽带，现在很多用户都在办理，真的很划算。流量超过30G后将限速。',
                                   'OTHER_REMARK': None, 'END_TIME': '0001-01-01T00:00:00',
                                   'END_TIME_STR': '0001-01-01 00:00:00', 'RECYCLE_HOURS': 0, 'STATUS': None,
                                   'PUB_TIME': '0001-01-01T00:00:00', 'FORBID_TIME': '0001-01-01T00:00:00',
                                   'FORBID_TIME_STR': '00:00:00', 'ALLOW_CALL_CNT': 0, 'CALLED_HOURS': 0,
                                   'CLIENT_NAME': None, 'SERVER_NAME': None, 'RECORDS': 0},
                                  {'ID': 84, 'PROD_NAME': '118元大流量资费迁转',
                                   'CALL_REMARK': '推荐您升级118元大流量套餐，可享受国内流量20GB+400分钟语音通话（200分钟国内+200分钟省内）+100M的宽带，现在很多用户都在办理，真的很划算。流量超过20G后将限速。',
                                   'OTHER_REMARK': None, 'END_TIME': '0001-01-01T00:00:00',
                                   'END_TIME_STR': '0001-01-01 00:00:00', 'RECYCLE_HOURS': 0, 'STATUS': None,
                                   'PUB_TIME': '0001-01-01T00:00:00', 'FORBID_TIME': '0001-01-01T00:00:00',
                                   'FORBID_TIME_STR': '00:00:00', 'ALLOW_CALL_CNT': 0, 'CALLED_HOURS': 0,
                                   'CLIENT_NAME': None, 'SERVER_NAME': None, 'RECORDS': 0},
                                  {'ID': 91, 'PROD_NAME': '50元大流量包加量不加价（送30元话费三个月）',
                                   'CALL_REMARK': '推荐您办理50元10G大流量包，包含10G全国流量，现在办理还可以赠送90元话费（分三个月），相当于前三个月跟现在花一样的钱就可以享受10G大流量包。活动期内流量包不能更改或取消，流量包内的流量不能结转、共享和转赠，3个月活动结束后按正常50元/月收取功能费，您可自行更改其他流量套餐。',
                                   'OTHER_REMARK': None, 'END_TIME': '0001-01-01T00:00:00',
                                   'END_TIME_STR': '0001-01-01 00:00:00', 'RECYCLE_HOURS': 0, 'STATUS': None,
                                   'PUB_TIME': '0001-01-01T00:00:00', 'FORBID_TIME': '0001-01-01T00:00:00',
                                   'FORBID_TIME_STR': '00:00:00', 'ALLOW_CALL_CNT': 0, 'CALLED_HOURS': 0,
                                   'CLIENT_NAME': None, 'SERVER_NAME': None, 'RECORDS': 0},
                                  {'ID': 90, 'PROD_NAME': '50元10G大流量包推荐',
                                   'CALL_REMARK': '推荐您办理50元10G大流量包，包含10G全国流量，现在很多客户都办了真的很划算。', 'OTHER_REMARK': None,
                                   'END_TIME': '0001-01-01T00:00:00', 'END_TIME_STR': '0001-01-01 00:00:00',
                                   'RECYCLE_HOURS': 0, 'STATUS': None, 'PUB_TIME': '0001-01-01T00:00:00',
                                   'FORBID_TIME': '0001-01-01T00:00:00', 'FORBID_TIME_STR': '00:00:00',
                                   'ALLOW_CALL_CNT': 0, 'CALLED_HOURS': 0, 'CLIENT_NAME': None, 'SERVER_NAME': None,
                                   'RECORDS': 0}, {'ID': 87, 'PROD_NAME': '168元大流量资费推荐',
                                                   'CALL_REMARK': '推荐您升级168元大流量套餐，可享受国内流量30GB+800分钟语音通话（400分钟国内+400分钟省内）+两条100M的宽带，现在很多用户都在办理，真的很划算。流量超过30G后将限速。',
                                                   'OTHER_REMARK': None, 'END_TIME': '0001-01-01T00:00:00',
                                                   'END_TIME_STR': '0001-01-01 00:00:00', 'RECYCLE_HOURS': 0,
                                                   'STATUS': None, 'PUB_TIME': '0001-01-01T00:00:00',
                                                   'FORBID_TIME': '0001-01-01T00:00:00', 'FORBID_TIME_STR': '00:00:00',
                                                   'ALLOW_CALL_CNT': 0, 'CALLED_HOURS': 0, 'CLIENT_NAME': None,
                                                   'SERVER_NAME': None, 'RECORDS': 0},
                                  {'ID': 89, 'PROD_NAME': '30元10G大流量包半价享',
                                   'CALL_REMARK': '推荐您办理50元10G大流量包，包含10G全国流量，现在办理还可以赠送90元话费（分三个月），相当于前三个月跟现在花一样的钱就可以享受10G大流量包。活动期内流量包不能更改或取消，流量包内的流量不能结转、共享和转赠，3个月活动结束后按正常50元/月收取功能费，您可自行更改其他流量套餐。',
                                   'OTHER_REMARK': None, 'END_TIME': '0001-01-01T00:00:00',
                                   'END_TIME_STR': '0001-01-01 00:00:00', 'RECYCLE_HOURS': 0, 'STATUS': None,
                                   'PUB_TIME': '0001-01-01T00:00:00', 'FORBID_TIME': '0001-01-01T00:00:00',
                                   'FORBID_TIME_STR': '00:00:00', 'ALLOW_CALL_CNT': 0, 'CALLED_HOURS': 0,
                                   'CLIENT_NAME': None, 'SERVER_NAME': None, 'RECORDS': 0}], 'CALL_REMARK': None,
                    'BELONG_AREA': None, 'PHONE_NO': None, 'REFERENCE_INFO1': None, 'REFERENCE_INFO2': None,
                    'REFERENCE_INFO3': None, 'STATUS': None, 'USER_ID': 0, 'OP_TIME': '0001-01-01T00:00:00',
                    'OPER_RESULT': '', 'IF_ANSWERED': True, 'IS_PROD_END': False,
                    'FINISHED_TIME': '0001-01-01T00:00:00', 'RESULT_LIST': None, 'IF_RECALL': False,
                    'IF_MAX_LATER': False}}

    result = {"code": 0, "msg": None,
              "data": {"ID": None, "PROD_ID": 0, "PROD_ID_END": 0, "PROD_NAME_END": None, "PROD_NAME": "198元大流量资费推荐",
                       "PROD_LIST": None,
                       "CALL_REMARK": "推荐您升级198元大流量套餐，可享受国内流量40GB+1000分钟语音通话（500分钟国内+500分钟省内）+两条100M的宽带，现在很多用户都在办理，真的很划算。流量超过40G后将限速。",
                       "BELONG_AREA": None, "PHONE_NO": None, "REFERENCE_INFO1": None, "REFERENCE_INFO2": None,
                       "REFERENCE_INFO3": None, "STATUS": None, "USER_ID": 0, "OP_TIME": "\/Date(-62135596800000)\/",
                       "OPER_RESULT": None, "IF_ANSWERED": True, "IS_PROD_END": False,
                       "FINISHED_TIME": "\/Date(-62135596800000)\/", "RESULT_LIST": None, "IF_RECALL": False,
                       "IF_MAX_LATER": False}}
    return HttpResponse(json.dumps(result, ensure_ascii=False), content_type="application/json,charset=utf-8")


def onGetCallSaleMobile(request):
    param_phone_no = request.GET.get('key')
    try:
        user_yhxx_list = models.yhxx.objects.filter(outcall_flag=0)
    except ObjectDoesNotExist:
        user_yhxx_list = None

    # 判断是否非空
    if user_yhxx_list is not None:
        print(user_yhxx_list[0].phone_no)
        result = {"code": 0, "Result": []}
    else:
        result = {"code": 0, "Result": []}

    res = {"code": 0, "msg": None,
              "data": {"ID": None, "PROD_ID": 0, "PROD_ID_END": 0, "PROD_NAME_END": None, "PROD_NAME": "198元大流量资费推荐",
                       "PROD_LIST": None,
                       "CALL_REMARK": "推荐您升级198元大流量套餐，可享受国内流量40GB+1000分钟语音通话（500分钟国内+500分钟省内）+两条100M的宽带，现在很多用户都在办理，真的很划算。流量超过40G后将限速。",
                       "BELONG_AREA": None, "PHONE_NO": aesmysql.decrypt_mysql(cryptoCode, user_yhxx_list[0].phone_no), "REFERENCE_INFO1": user_yhxx_list[0].main_prod_name, "REFERENCE_INFO2": user_yhxx_list[0].bd,
                       "REFERENCE_INFO3": user_yhxx_list[0].prod_name, "STATUS": None, "USER_ID": 0, "OP_TIME": "\/Date(-62135596800000)\/",
                       "OPER_RESULT": None, "IF_ANSWERED": True, "IS_PROD_END": False,
                       "FINISHED_TIME": "\/Date(-62135596800000)\/", "RESULT_LIST": None, "IF_RECALL": False,
                       "IF_MAX_LATER": False}}


    return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")


def onSaveCallSale(request):
    param_phone_no = request.GET.get('PHONE_NO')
    oper_result = request.GET.get('OPER_RESULT')
    outcall_answered = request.GET.get('IF_ANSWERED')
    recommand_prod_id = request.GET.get('CALL_REMARK')
    try:
        user_yhxx = models.yhxx.objects.get(phone_no=aesmysql.encrypt_mysql(cryptoCode, param_phone_no))
    except ObjectDoesNotExist:
        user_yhxx = None

    outcall_result = '0'
    if outcall_answered == 'true':
        outcall_result = oper_result

    onSaveAgentId = request.COOKIES.get('uid')
    print('onSaveAgentId: ' + onSaveAgentId)

    # 判断是否非空
    if user_yhxx is not None:
        user_yhxx.outcall_flag = 1
        user_yhxx.outcall_agent = onSaveAgentId
        user_yhxx.outcall_result = outcall_result
        user_yhxx.outcall_answered = outcall_answered
        user_yhxx.recommand_prod_id = recommand_prod_id
        user_yhxx.last_outcall_time = datetime.datetime.now()
        user_yhxx.save()
        print('outcall_flag saved: ' + aesmysql.decrypt_mysql(cryptoCode, user_yhxx.phone_no))

        result = {"code": 0, "msg": None,
               "data": {"ID": None, "PROD_ID": 0, "PROD_ID_END": 0, "PROD_NAME_END": None, "PROD_NAME": "198元大流量资费推荐",
                        "PROD_LIST": None,
                        "CALL_REMARK": "推荐您升级198元大流量套餐，可享受国内流量40GB+1000分钟语音通话（500分钟国内+500分钟省内）+两条100M的宽带，现在很多用户都在办理，真的很划算。流量超过40G后将限速。",
                        "BELONG_AREA": None, "PHONE_NO": aesmysql.encrypt_mysql(cryptoCode, user_yhxx.phone_no),
                        "REFERENCE_INFO1": None, "REFERENCE_INFO2": None,
                        "REFERENCE_INFO3": None, "STATUS": None, "USER_ID": 0,
                        "OP_TIME": "\/Date(-62135596800000)\/",
                        "OPER_RESULT": None, "IF_ANSWERED": True, "IS_PROD_END": False,
                        "FINISHED_TIME": "\/Date(-62135596800000)\/", "RESULT_LIST": None, "IF_RECALL": False,
                        "IF_MAX_LATER": False}}
    else:
        result = {"code": 0, "Result": []}

    return HttpResponse(json.dumps(result, ensure_ascii=False), content_type="application/json,charset=utf-8")

def login(request):
    return render(request, 'login.html')

def initPwdReset(request):
    return render(request, 'initPwdReset.html')

def onSetPwd(request):
    result = {"code": 0, "Result": []}

    return HttpResponse(json.dumps(result, ensure_ascii=False), content_type="application/json,charset=utf-8")

# code 2 reset 1 false 0 true
def onLogin(request):

    if request.method == 'POST':
        uname = request.POST.get('loginname')
        upwd = request.POST.get('psw')
        loginCode = request.POST.get('code')
        loginType = request.POST.get('type')

        isLogin = False
        result = {}
        if uname and upwd and loginType:
            u = authenticate(uname = uname, upwd = upwd, loginType = loginType, loginCode = loginCode)

            if u is None:
                result = {"code": 1, "msg": '登录失败，请检查账号与密码'}
            else:
                if u.is_active == 0:
                    result = {"code": 1, "msg": '用户未启用'}
                else:
                    print(uname, upwd)
                    request.session['is_login'] = True
                    request.session['uid'] = u.id
                    request.session['uname'] = u.username
                    result = {"code": 0, "msg": '登录成功'}
                    isLogin = True

    resp = HttpResponse(json.dumps(result, ensure_ascii=False), content_type="application/json,charset=utf-8")
    if isLogin == True:
        resp.set_cookie('uid', u.id, expires=60 * 60 * 24 * 7)
    return resp


def authenticate(uname, upwd, loginType, loginCode):
    if loginType == 'psw':

        try:
            encryptedPwd = aesmysql.encrypt_mysql(cryptoCode, upwd)
            u = models.agent.objects.get(username = uname, password = encryptedPwd)
            return u
        except:
            return None

    elif loginType == 'code':
        try:
            u = models.agent.objects.get(username = uname, tmp_code = loginCode)
            return u
        except:
            return None

    else:
        return None

def onLogout(request):
    request.session.flush()
    print("flush")

    return redirect("/login")

